<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <el-header class="app-header">
      <div class="header-title">图书管理系统</div>
      <el-tag type="success" effect="dark" class="connection-status">连接正常</el-tag>
    </el-header>

    <!-- 主内容区 -->
    <el-main class="app-main">
      <!-- 1. 图书评分分布模块 -->
      <el-card class="function-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>1. 图书评分分布</span>
            <el-tooltip content="各星级书籍占比统计" placement="top">
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <div class="card-content">
          <!-- 饼图容器 -->
          <div ref="ratingChart" class="chart-container"></div>
          <!-- 图例说明 -->
          <div class="chart-legend">
            <div v-for="item in ratingLegend" :key="item.star" class="legend-item">
              <span class="legend-color" :style="{ backgroundColor: item.color }"></span>
              <span>{{ item.label }}：{{ item.count }}本（{{ item.ratio }}%）</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 2. 作者影响力排名模块 -->
      <el-card class="function-card" shadow="never" >
        <template #header>
          <div class="card-header">
            <span>2. 作者影响力排名</span>
            <el-tooltip content="按作品数量+平均评分排序" placement="top">
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <div class="card-content">
          <!-- 作者排名表格 -->
          <el-table :data="authorRanking" stripe class="ranking-table">
            <el-table-column prop="rank" label="排名" width="80" align="center"></el-table-column>
            <el-table-column prop="author" label="作者" min-width="150"></el-table-column>
            <el-table-column prop="avgRating" label="平均评分" width="120" align="center">
              <template #default="row">
                <!-- 先判断 row 存在，再渲染 el-rate -->
                <el-rate v-if="row"
                         v-model="row.avgRating"
                         disabled
                         show-score
                         score-template="{value}">
                </el-rate>
              </template>
            </el-table-column>
            <el-table-column prop="workCount" label="作品数量" width="120" align="center"></el-table-column>
          </el-table>
          <div ref="authorChart" class="chart-container"></div>
        </div>
      </el-card>

      <!-- 3. 出版年份趋势模块 -->
      <el-card class="function-card" shadow="never" >
        <template #header>
          <div class="card-header">
            <span>3. 出版年份趋势</span>
            <el-tooltip content="年度书籍数量变化+年均增长率" placement="top">
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <div class="card-content">
          <!-- 折线图占位（后续对接后端） -->
            <div ref="trendChart" class="chart-container"></div>
          </div>
      </el-card>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts' // 引入 ECharts
import { InfoFilled } from '@element-plus/icons-vue'



// ———— 评分分布（饼图，原有逻辑不变） ————
const ratingData = [
  { star: 5, count: 45, ratio: 30, color: '#5470c6' },
  { star: 4, count: 35, ratio: 23.3, color: '#91cc75' },
  { star: 3, count: 30, ratio: 20, color: '#fac858' },
  { star: 2, count: 20, ratio: 13.3, color: '#ee6666' },
  { star: 1, count: 10, ratio: 6.7, color: '#73c0de' }
]
const ratingLegend = ratingData.map(item => ({ ...item }))
const ratingChart = ref(null)

// 评分分布饼图初始化（修改后）
const initRatingChart = () => {
  const chartDom = ratingChart.value;
  if (!chartDom) return console.error('[评分图表] 容器不存在！');
  try {
    const chart = echarts.init(chartDom);
    chart.setOption({
      tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c}本 ({d}%)' },
      series: [{
        name: '评分分布',
        type: 'pie',
        radius: ['40%', '70%'],
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        data: ratingData.map(item => ({
          value: item.count,
          name: `${item.star}星`,
          itemStyle: { color: item.color }
        }))
      }]
    });
    window.addEventListener('resize', () => chart.resize());
  } catch (error) {
    console.error('[评分图表] 初始化失败：', error);
  }
};



// 🔹 模拟作者-作品数量数据
const authorRanking = ref([
  { rank: 1, author: '艾萨克·阿西莫夫', avgRating: 4.8, workCount: 54 },
  { rank: 2, author: 'J.K.罗琳', avgRating: 4.7, workCount: 7 },
  { rank: 3, author: '刘慈欣', avgRating: 4.6, workCount: 13 },
  { rank: 4, author: '余华', avgRating: 4.5, workCount: 11 },
  { rank: 5, author: '村上春树', avgRating: 4.4, workCount: 15 }
])
// 🔹 柱状图模拟数据（作者名 + 作品数）
const authorWorkData = ref([
  { author: 'J.K.罗琳', count: 7 },
  { author: '刘慈欣', count: 13 },
  { author: '余华', count: 11 },
  { author: '村上春树', count: 15 },
  { author: '东野圭吾', count: 9 },
  { author: '鲁迅', count: 20 },
  { author: '钱钟书', count: 8 },
  { author: '张爱玲', count: 6 }
])
const authorChart = ref(null)

// 作者影响力排名柱状图初始化（修改后）
const initAuthorChart = () => {
  const chartDom = authorChart.value;
  if (!chartDom) return console.error('[作者图表] 容器不存在！');
  try {
    const chart = echarts.init(chartDom);
    chart.setOption({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      xAxis: {
        type: 'category',
        data: authorWorkData.value.map(item => item.author),
        axisLabel: { rotate: 45, interval: 0 }
      },
      yAxis: { type: 'value', name: '作品数量' },
      series: [{
        name: '作品数量',
        type: 'bar',
        data: authorWorkData.value.map(item => item.count),
        itemStyle: { color: '#5470c6' }
      }]
    });
    window.addEventListener('resize', () => chart.resize());
  } catch (error) {
    console.error('[作者图表] 初始化失败：', error);
  }
};



// ———— 出版年份趋势（折线图，新增逻辑） ————
// 🔹 模拟出版年份-书籍数量数据
const trendData = ref([
  { year: 2018, count: 80 }, // year 改为数值类型
  { year: 2019, count: 120 },
  { year: 2020, count: 150 },
  { year: 2021, count: 200 },
  { year: 2022, count: 250 },
  { year: 2023, count: 300 }
]);

const initTrendChart = () => {
  console.log('[趋势图表] 开始初始化');
  const chartDom = trendChart.value;
  if (!chartDom) {
    console.error('[趋势图表] 容器不存在！');
    return;
  }
  try {
    const chart = echarts.init(chartDom);
    const option = {
      tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
      xAxis: {
        type: 'category',
        data: trendData.value.map(item => item.year.toString()), // 转为字符串（ECharts 要求）
        axisLabel: { rotate: 0 }
      },
      yAxis: { type: 'value', name: '书籍数量' },
      series: [{
        name: '年度数量',
        type: 'line',
        data: trendData.value.map(item => item.count),
        itemStyle: { color: '#91cc75' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(145, 204, 117, 0.5)' },
            { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
          ])
        }
      }]
    };
    chart.setOption(option);
    window.addEventListener('resize', () => chart.resize());
    console.log('[趋势图表] 初始化成功');
  } catch (error) {
    console.error('[趋势图表] 初始化失败：', error);
  }
};

onMounted(() => {
  initRatingChart(); // 仅测试评分饼图
  // initAuthorChart(); // 注释作者模块
  // initTrendChart(); // 注释趋势模块
});

</script>

<style scoped>
/* 全局容器（不变） */
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏（不变） */
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 0 20px;
}
.header-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}
.connection-status {
  font-size: 14px;
  padding: 4px 8px;
}

/* 主内容区（不变） */
.app-main {
  flex: 1;
  padding: 20px;
  background-color: #f0f2f5;
  overflow-y: auto;
}

/* 功能导航 Tabs（不变） */
.function-tabs {
  margin-bottom: 20px;
}

/* 功能卡片（不变） */
.function-card {
  margin-bottom: 20px;
  border-radius: 8px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.card-content {
  padding: 20px;
}

/* 图表容器（统一设置宽高，确保图表显示） */
.chart-container {
  width: 100%;
  height: 400px;
}

/* 排名表格（不变） */
.ranking-table {
  margin-bottom: 20px;
}

/* 图例说明（不变） */
.chart-legend {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.legend-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}
.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}

/* 占位样式（可选，若不需要可删除） */
.chart-placeholder {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 8px;
  color: #999;
  font-size: 16px;
}
</style>